<!--
 * @file layout.vue
 * @description 应用程序的主布局组件，包含侧边栏、顶部导航和内容区域
 * @author Logan.Li
-->
<template>
    <div class="common-layout">
        <!-- 整个应用的容器 -->
        <el-container>
            <!-- 侧边栏 -->
            <el-aside :width="sidebarWidth">
                <!-- 侧边栏菜单：配置菜单主题和行为 -->
                <el-menu default-active="2" class="el-menu-vertical-demo" background-color="#304156"
                    text-color="#FFFFFF" active-text-color="#007BFF" @open="handleOpen" @close="handleClose" router
                    :collapse="isCollapse" :collapse-transition="false">
                    <!-- Logo 和标题区域 -->
                    <div class="logo-title">
                        <img src="../assets/vue.svg" alt="Logo" />
                        <!-- 根据侧边栏折叠状态动态显示标题 -->
                        <span v-if="!isCollapse">DevOps 管理系统</span>
                    </div>
                    <!-- 动态渲染路由配置的菜单项 -->
                    <template v-for="menu in routerStore.filteredMenus" :key="menu.path">
                        <!-- 过滤登录页和根路由重定向 -->
                        <template v-if="menu.name !== 'Login' && menu.path !== '/'">
                            <!-- 无子菜单的菜单项渲染 -->
                            <el-menu-item v-if="!menu.children" :index="menu.path">
                                <el-icon v-if="menu.icon">
                                    <component :is="menu.icon" />
                                </el-icon>
                                <span>{{ menu.name }}</span>
                            </el-menu-item>
                            <!-- 有子菜单的菜单项渲染 -->
                            <el-sub-menu v-else :index="menu.path">
                                <template #title>
                                    <el-icon v-if="menu.icon">
                                        <component :is="menu.icon" />
                                    </el-icon>
                                    <span>{{ menu.name }}</span>
                                </template>
                                <!-- 子菜单项循环渲染 -->
                                <el-menu-item v-for="child in menu.children" :key="child.path" :index="child.path">
                                    <el-icon v-if="child.icon">
                                        <component :is="child.icon" />
                                    </el-icon>
                                    <span>{{ child.name }}</span>
                                </el-menu-item>
                            </el-sub-menu>
                        </template>
                    </template>
                </el-menu>
            </el-aside>
            <!-- 主内容区域容器 -->
            <el-container>
                <!-- 顶部导航栏 -->
                <el-header>
                    <div>
                        <!-- 侧边栏折叠控制按钮 -->
                        <el-icon :size="25" @click="toggleCollapse">
                            <!-- 根据折叠状态显示不同图标 -->
                            <template v-if="isCollapse">
                                <Expand />
                            </template>
                            <template v-else>
                                <Fold />
                            </template>
                        </el-icon>
                    </div>
                    <div>
                        <!-- 用户信息下拉菜单 -->
                        <el-dropdown>
                            <!-- 用户头像和下拉指示器 -->
                            <div class="header-dropdown">
                                <img src="../assets/anonymous.jpeg" class="avator-image" alt="Avatar" />
                                <el-icon class="el-icon--right">
                                    <ArrowDown />
                                </el-icon>
                            </div>
                            <!-- 下拉菜单选项 -->
                            <template #dropdown>
                                <el-dropdown-menu>
                                    <el-dropdown-item @click="handleUserCenter">个人中心</el-dropdown-item>
                                    <el-dropdown-item @click="handlePasswordChange">修改密码</el-dropdown-item>
                                    <el-dropdown-item @click="handleLogout">退出登录</el-dropdown-item>
                                </el-dropdown-menu>
                            </template>
                        </el-dropdown>
                    </div>
                </el-header>
                <!-- 主要内容区域 -->
                <el-main>
                    <!-- 路由视图容器 -->
                    <router-view></router-view>
                </el-main>
            </el-container>
        </el-container>
    </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue';
import { useUserStore } from '../stores/user';
import { useRouterStore } from '../stores/router';
import { useRouter } from 'vue-router';
import { ElMessageBox } from 'element-plus';

// 初始化路由和用户状态管理
const router = useRouter();
const userStore = useUserStore();
const routerStore = useRouterStore();

// 组件状态管理
const isCollapse = ref(false);
const showPasswordDialog = ref(false);
const fullWidth = ref(document.documentElement.clientWidth);

// 计算属性
const sidebarWidth = computed(() => isCollapse.value ? '64px' : '200px');
const username = computed(() => sessionStorage.getItem('username') || '未知');

// 生命周期钩子
onMounted(async () => {
    await initializeRouteAndMenu();
    // 添加窗口大小监听
    window.addEventListener('resize', handleResize);
    handleResize();
});

onBeforeUnmount(() => {
    window.removeEventListener('resize', handleResize);
});

// 初始化路由和菜单的方法
async function initializeRouteAndMenu() {
    try {
        // 检查用户登录状态
        const token = sessionStorage.getItem('token');
        console.log('当前登录状态:', token ? '已登录' : '未登录');
        
        if (!token) {
            console.warn('未检测到登录令牌，重定向到登录页面');
            router.push('/login');
            return;
        }

        // 加载用户信息和权限
        console.log('开始加载用户信息...');
        await userStore.getUserInfo();
        console.log('用户信息加载完成，权限列表:', userStore.permissions);
        
        // 根据用户权限加载动态路由
        console.log('开始生成动态路由...');
        await routerStore.generateRoutes(userStore.permissions);
        console.log('动态路由生成完成，菜单列表:', routerStore.filteredMenus);
        
        // 设置默认激活的菜单项
        const currentRoute = router.currentRoute.value;
        if (currentRoute.path !== '/login') {
            const defaultActive = currentRoute.path;
            const menuElement = document.querySelector('.el-menu');
            if (menuElement) {
                menuElement.setAttribute('default-active', defaultActive);
                console.log('设置默认激活菜单项:', defaultActive);
            } else {
                console.warn('未找到菜单元素，无法设置默认激活项');
            }
        }
    } catch (error) {
        console.error('初始化路由和菜单失败:', error);
        // 添加更详细的错误信息
        const errorMessage = error.response?.data?.message || error.message || '未知错误';
        console.error('详细错误信息:', errorMessage);
        
        ElMessageBox.alert(`系统初始化失败: ${errorMessage}`, '错误', {
            confirmButtonText: '确定',
            type: 'error',
            callback: () => {
                console.log('用户确认错误提示，执行登出操作');
                sessionStorage.clear();
                router.push('/login');
            }
        });
    }
}

// 方法定义
function handleResize() {
    fullWidth.value = document.documentElement.clientWidth;
    if (fullWidth.value < 1000) {
        isCollapse.value = true;
    } else {
        isCollapse.value = false;
    }
}

function toggleCollapse() {
    isCollapse.value = !isCollapse.value;
}

function handleOpen(key, keyPath) {
    console.log(`菜单项打开: ${key}`, keyPath);
}

function handleClose(key, keyPath) {
    console.log(`菜单项关闭: ${key}`, keyPath);
}

async function handleLogout() {
    try {
        await ElMessageBox.confirm('确认退出登录吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        });
        sessionStorage.clear();
        router.push('/login');
    } catch (error) {
        console.log('取消退出登录');
    }
}

function handlePasswordChange() {
    showPasswordDialog.value = true;
}

function handleUserCenter() {
    router.push('/profile/index');
}
</script>

<style scoped>
.aside {
    transition: all 0.5s;
    background-color: #304156;
}

@media (max-width: 767px) {
    .el-header {
        padding: 0 10px;
    }

    .el-main {
        padding: 10px;
    }

    .logo-title span {
        display: none;
    }
}

/* 头部导航栏样式 */
.el-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

/* 主内容区域样式 */
.el-main {
    background: #f5f5f5;
}

/* 布局容器样式 */
.common-layout,
.el-container,
.el-menu-vertical-demo {
    height: 100%;
}

/* Logo区域样式 */
.logo-title {
    display: flex;
    align-items: center;
    margin-bottom: 12px;
}

/* Logo图片样式 */
.logo-title img {
    width: 30px;
    height: 30px;
    margin-left: 15px;
    margin-top: 16px;
}

/* Logo文字样式 */
.logo-title span {
    color: #fff;
    font-weight: bold;
    font-size: 16px;
    margin-left: 10px;
    position: relative;
    margin-top: 16px;
}

/* 用户头像样式 */
.avator-image {
    width: 40px;
    height: 40px;
    border-radius: 20%;
    margin-right: 8px;
}

/* 用户下拉菜单样式 */
.header-dropdown {
    display: flex;
    align-items: center;
    cursor: pointer;
}
</style>